<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="70px">
      <el-form-item label="学员名称" prop="studentName">
        <el-input v-model="queryParams.studentName" placeholder="请输入学员名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="课程名称" prop="curriculumName">
        <el-input v-model="queryParams.curriculumName" placeholder="请输入课程名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="销售" prop="salesName">
        <el-input v-model="queryParams.salesName" placeholder="请输入学员销售" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['jiaopei:curriculumStudent:add']">购买课程</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['jiaopei:curriculumStudent:edit']"-->
      <!--        >修改</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['jiaopei:curriculumStudent:remove']">删除课程</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['jiaopei:curriculumStudent:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="curriculumStudentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" min-width="40" show-overflow-tooltip prop="id" v-if="true" />
      <el-table-column label="学员名称" align="center" prop="studentVo.name" min-width="80" show-overflow-tooltip />
      <!--      <el-table-column label="课程ID" align="center" prop="curriculumId" />-->
      <el-table-column label="课时" align="center" prop="lessonHours" min-width="80" show-overflow-tooltip />
      <!--      <el-table-column label="剩余课时" align="center" prop="surplus" />-->
      <el-table-column label="课程名称" align="center" prop="curriculumName" min-width="100" show-overflow-tooltip />
      <el-table-column label="价格" align="center" prop="price" min-width="80" show-overflow-tooltip />
      <el-table-column label="购买时间" align="center" prop="createdDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="approval" min-width="80" show-overflow-tooltip />
      <el-table-column label="销售" align="center" prop="salesVo.nickName" min-width="80" show-overflow-tooltip />
      <el-table-column label="来源" align="center" prop="source">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.source_type" :value="scope.row.source" />
        </template>
      </el-table-column>
      <el-table-column label="付款状态" align="center" prop="paymentStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.payment_status" :value="scope.row.paymentStatus" />
        </template>
      </el-table-column>
      <el-table-column label="付款时间" align="center" prop="paymentDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.paymentDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" min-width="100" show-overflow-tooltip />
           <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
             <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['jiaopei:curriculumStudent:edit']"
                >修改</el-button>
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-delete"-->
      <!--            @click="handleDelete(scope.row)"-->
      <!--            v-hasPermi="['jiaopei:curriculumStudent:remove']"-->
      <!--          >删除课程</el-button>-->
             </template>
           </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改课程学员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学员" prop="studentName">
          <!-- <el-input v-model="form.studentName" readonly placeholder="请选择学员" >
            <i  class="el-icon-edit el-input__icon" slot="suffix" @click="openSelectStudent" />
          </el-input> -->
          <group-select class="form-item-input-style" v-model="form.studentId" :group_list="['student']"
            placeholder="请选择学员" />
        </el-form-item>
        <el-form-item label="课程名称" prop="curriculumName">
          <!-- <el-input v-model="form.curriculumName" readonly placeholder="请选择课程" >
            <i  class="el-icon-edit el-input__icon" slot="suffix" @click="openSelectCurriculum" />
          </el-input> -->
          <group-select class="form-item-input-style" v-model="form.curriculumId" :group_list="['curriculum']"
            placeholder="请选择课程" @curriculumListChange="curriculumListChange" />
        </el-form-item>
        <!--        <el-form-item label="课程名称" prop="curriculumName">-->
        <!--          <el-input v-model="form.curriculumName" disabled placeholder="请输入课程名称" />-->
        <!--        </el-form-item>-->
        <el-form-item label="课时" prop="lessonHours">
          <el-input-number v-model="form.lessonHours" :min="1" :max="99999" placeholder="请输入课时"></el-input-number>
        </el-form-item>
        <!--        <el-form-item label="剩余课时" prop="lessonHours">-->
        <!--          <el-input v-model="form.lessonHours" disabled placeholder="请输入剩余课时" />-->
        <!--        </el-form-item>-->
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格"
            onkeyup="value=value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3').replace(/[^\d.]/g,'')" />
        </el-form-item>
        <el-form-item label="审批人" prop="approval">
          <el-input v-model="form.approval" placeholder="请输入审批人" />
        </el-form-item>
        <el-form-item label="销售" prop="salesName">
          <!-- <el-input v-model="form.salesName" readonly placeholder="请选择销售" >
            <i  class="el-icon-edit el-input__icon" slot="suffix" @click="openSelectUser1" />
          </el-input> -->
          <group-select class="form-item-input-style" v-model="form.salesId" :group_query="salesGroupQuery"
            :group_list="['user']" placeholder="请选择销售" />
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-select v-model="form.source" placeholder="请选择来源">
            <el-option v-for="dict in dict.type.source_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="付款状态" prop="paymentStatus">
          <el-select v-model="form.paymentStatus" placeholder="请选择付款状态">
            <el-option v-for="dict in dict.type.payment_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="付款时间" prop="paymentDate">
          <el-date-picker clearable v-model="form.paymentDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择付款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" />
        </el-form-item>

        <!--        <el-form-item label="创建时间" prop="createdDate">-->
        <!--          <el-date-picker clearable-->
        <!--            v-model="form.createdDate"-->
        <!--            type="datetime"-->
        <!--            value-format="yyyy-MM-dd HH:mm:ss"-->
        <!--            placeholder="请选择创建时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <select-curriculum ref="selectCurriculum" @ok="selectCurriculumOk" />

    <select-student ref="selectStudent" @ok="openSelectStudentOk" />

    <select-user ref="select1" @ok="selectUserOk1" />


  </div>
</template>

<script>
import { listCurriculumStudent, getCurriculumStudent, delCurriculumStudent, addCurriculumStudent, updateCurriculumStudent } from "@/api/jiaopei/curriculumStudent";
import selectCurriculum from "@/views/jiaopei/class/selectCurriculum";
import selectStudent from "@/views/jiaopei/student/selectStudent";
import selectUser from "@/views/jiaopei/class/selectUser";
import groupSelect from "@/views/components/groupSelect";
export default {
  name: "CurriculumStudent",
  dicts: ['source_type', 'payment_status'],
  props: {
    studentId: {
      default: null,
    },
  },
  components: { selectUser, selectCurriculum, selectStudent, groupSelect },
  computed: {
    salesGroupQuery() {
      var value = {
        'user': {
          teacher: '0,1,2'
        }
      }
      return value
    }
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程学员表格数据
      curriculumStudentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: undefined,
        salesName: undefined,
        curriculumName: undefined,
        studentId: this.studentId,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "ID不能为空", trigger: "blur" }
        ],
        studentId: [
          { required: true, message: "学员不能为空", trigger: "blur" }
        ],
        salesId: [
          { required: true, message: "销售不能为空", trigger: "blur" }
        ],
        curriculumId: [
          { required: true, message: "课程不能为空", trigger: "blur" }
        ],
        lessonHours: [
          { required: true, message: "课时不能为空", trigger: "blur" }
        ],
        // surplus: [
        //   { required: true, message: "剩余课时不能为空", trigger: "blur" }
        // ],
        // curriculumName: [
        //   { required: true, message: "课程名称不能为空", trigger: "blur" }
        // ],
        // price: [
        //   { required: true, message: "价格不能为空", trigger: "blur" }
        // ],
        // createdDate: [
        //   { required: true, message: "创建时间不能为空", trigger: "blur" }
        // ]
      },
      leftUrl: undefined,
      curriculumList:[],//课程列表
      historyForm:{},//历史表单
      isUpdate:false,
    };
  },
  watch: {
    $route: {
      immediate: true,
      handler(to, from) {
        if (to.path == '/yewu/curriculumStudent') {
          if (this.leftUrl != to.fullPath) {
            if (this.$route.query['studentName']) {
              this.queryParams.studentName = this.$route.query['studentName'];
            }

            this.getList();
          }
          this.leftUrl = to.fullPath;
        }
      }
    },
    'form.curriculumId': {
      handler(newValue, oldValue) {
        var curriculum = this.curriculumList.find(item => {
          return item.id == newValue;
        });
        if(curriculum && !this.isUpdate){
          this.form.price = curriculum.price;
          this.form.lessonHours = curriculum.lessonHours;
        }
        // this.isUpdate = false;
      },
      deep: true,
      immediate: true
    },
  },
  created() {
    if (this.$route.query['studentName']) {
      this.queryParams.studentName = this.$route.query['studentName'];
    }


    this.getList();
  },
  methods: {
    /** 查询课程学员列表 */
    getList() {
      this.loading = true;


      listCurriculumStudent(this.queryParams).then(response => {
        this.curriculumStudentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      const date = new Date();
      this.form = {
        id: undefined,
        studentId: this.studentId,
        studentName: undefined,
        curriculumId: undefined,
        lessonHours: undefined,
        surplus: undefined,
        curriculumName: undefined,
        approval: undefined,
        remarks: undefined,
        price: undefined,
        salesId: undefined,
        salesName: undefined,
        createdDate: undefined,
        source: "1",
        paymentStatus: "1",
        paymentDate: this.formatDateTime(date),
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isUpdate = false;
      this.open = true;
      this.title = "学员购买课程";

      if (this.$route.query['studentName']) {
        this.form.studentName = this.$route.query['studentName'];
      }
      if (this.$route.query['studentId']) {
        this.form.studentId = this.$route.query['studentId'];
      }


    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCurriculumStudent(id).then(response => {
        this.loading = false;
        var data = response.data;
        this.form = data;
        this.historyForm = JSON.parse(JSON.stringify(data));
        this.isUpdate = true;
        this.open = true;
        this.title = "修改学员购买课程";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            console.log(this.form.paymentStatus);
            console.log(this.historyForm.paymentStatus);
            if(this.form.paymentStatus != this.historyForm.paymentStatus){
              //修改了状态
              const date = new Date();
              this.form.paymentDate = this.formatDateTime(date);
            }

            updateCurriculumStudent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addCurriculumStudent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除课程学员编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delCurriculumStudent(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jiaopei/curriculumStudent/export', {
        ...this.queryParams
      }, `curriculumStudent_${new Date().getTime()}.xlsx`)
    },
    /** 打开选择用户 */
    openSelectCurriculum() {
      this.$refs.selectCurriculum.show();
    },
    selectCurriculumOk(row) {
      this.form.curriculumId = row['id'];
      this.form.curriculumName = row['name'];
      this.form.lessonHours = row['lessonHours'];
      this.form.surplus = row['lessonHours'];
      this.form.price = row['price'];

      this.$forceUpdate();
    },
    openSelectStudent() {
      this.$refs.selectStudent.show();
    },
    openSelectStudentOk(row) {
      this.form.studentId = row['id'];
      this.form.studentName = row['name'];
    },
    openSelectUser1() {
      this.$refs.select1.show(true, '2');
    },
    selectUserOk1(row) {
      this.form.salesId = row['userId'];
      this.form.salesName = row['nickName'];
      this.$forceUpdate();
    },
    formatDateTime(date) {
      // 格式化日期时间为字符串，例如：'2023-04-01 12:00:00'
      // 根据需要自定义格式
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
    },
    curriculumListChange(list){
      this.curriculumList = list;
    }
  }
};
</script>
